<template>
  <div class="weapon-display">
    <!-- 页面标题 -->
    <div class="page-header">
      
      <p>探索崩坏3中的各种武器</p>
    </div>

    <!-- 加载状态 -->
    <div v-if="loading" class="loading-container">
      <div class="loading-spinner"></div>
      <p>加载中...</p>
    </div>

    <!-- 错误状态 -->
    <div v-else-if="error" class="error-container">
      <p>{{ error }}</p>
      <button @click="loadData" class="retry-btn">重试</button>
    </div>

    <!-- 主要内容 -->
    <div v-else>
      <!-- 搜索和筛选区域 -->
      <div class="search-section">
        <div class="search-container">
          <div class="search-input-wrapper">
            <input 
              v-model="searchQuery" 
              type="text" 
              placeholder="搜索武器名称..." 
              class="search-input"
              @input="handleSearch"
            >
            <i class="search-icon">🔍</i>
          </div>
          
          <div class="filter-container">
            <select v-model="selectedHero" @change="handleFilter" class="hero-filter">
              <option value="">所有英雄</option>
              <!-- 修复: 使用 hero.id 作为 key 和 value，确保选择的值为真实的英雄ID -->
              <option v-for="hero in heroList" :key="hero.id" :value="hero.id">
                {{ hero.heroName }}
              </option>
            </select>
          </div>
        </div>
      </div>

      <!-- 武器网格 -->
      <div class="weapons-grid">
        <div 
          v-for="weapon in filteredWeapons" 
          :key="weapon.weaponId" 
          class="weapon-card"
          @click="selectWeapon(weapon)"
        >
          <div class="weapon-image">
            <img 
              :src="weapon.weaponSkillUrl || '/default-weapon.png'" 
              :alt="weapon.weaponName"
              @error="handleImageError"
            >
          </div>
          <div class="weapon-info">
            <h3 class="weapon-name">{{ weapon.weaponName }}</h3>
          </div>
        </div>
      </div>

      <!-- 空状态 -->
      <div v-if="filteredWeapons.length === 0" class="empty-state">
        <div class="empty-icon">⚔️</div>
        <h3>暂无武器数据</h3>
        <p>{{ searchQuery || selectedHero ? '没有找到符合条件的武器' : '暂时没有武器数据' }}</p>
      </div>
    </div>

    <!-- 武器详情模态框 -->
    <div v-if="showDetailModal" class="modal-overlay" @click="closeDetailModal">
      <div class="modal-content weapon-detail-modal" @click.stop>
        <div class="modal-header">
          <h2>{{ selectedWeapon?.weaponName }}</h2>
          <button @click="closeDetailModal" class="close-btn">×</button>
        </div>
        <div class="modal-body">
          <div class="weapon-detail-content">
            <div class="weapon-image-large">
              <img 
                :src="selectedWeapon?.weaponSkillUrl || '/default-weapon.png'" 
                :alt="selectedWeapon?.weaponName"
                @error="handleImageError"
              >
            </div>
            <div class="weapon-details">
              <div class="detail-section">
                <h3>基础属性</h3>
                <div class="stats-grid">
                  <div class="stat-item">
                    <span class="stat-label">攻击力</span>
                    <span class="stat-value">{{ selectedWeapon?.attack }}</span>
                  </div>
                  <div class="stat-item">
                    <span class="stat-label">暴击率</span>
                    <span class="stat-value">{{ selectedWeapon?.critRate }}%</span>
                  </div>
                </div>
              </div>
              
              <div class="detail-section" v-if="getHeroInfo(selectedWeapon?.heroId)">
                <h3>适宜英雄</h3>
                <div class="hero-info" @click="goToHeroDetail(selectedWeapon?.heroId)">
                  <div class="hero-avatar">
                    <img 
                      :src="getHeroInfo(selectedWeapon?.heroId)?.smallIconUrl || '/default-hero.png'" 
                      :alt="getHeroInfo(selectedWeapon?.heroId)?.heroName"
                      @error="handleHeroImageError"
                    >
                  </div>
                  <div class="hero-details">
                    <span class="hero-name">{{ getHeroInfo(selectedWeapon?.heroId)?.heroName }}</span>
                  </div>
                </div>
              </div>
              
              <div class="detail-section" v-if="selectedWeapon?.weaponBackground">
                <h3>武器背景</h3>
                <p class="weapon-description">{{ selectedWeapon.weaponBackground }}</p>
              </div>
              
              <div class="detail-section" v-if="selectedWeapon?.weaponSkill">
                <h3>武器技能</h3>
                <p class="weapon-skill">{{ selectedWeapon.weaponSkill }}</p>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue'
import { ElMessage } from 'element-plus'
import { weaponApi } from '../api/weapon.js'
import { heroApi } from '../api/hero.js'

// 响应式数据
const weapons = ref([])
const heroList = ref([])
const searchQuery = ref('')
const selectedHero = ref('')
const selectedWeapon = ref(null)
const showDetailModal = ref(false)
const loading = ref(true)
const error = ref(null)

// 计算属性
const filteredWeapons = computed(() => {
  let filtered = weapons.value
  
  // 按名称搜索
  if (searchQuery.value) {
    const query = searchQuery.value.toLowerCase()
    filtered = filtered.filter(weapon => 
      weapon.weaponName.toLowerCase().includes(query)
    )
  }
  
  return filtered
})

// 方法
const loadData = async () => {
  try {
    loading.value = true
    error.value = null
    
    // 并行加载武器和英雄数据
    const [weaponResponse, heroResponse] = await Promise.all([
      weaponApi.getAllWeapons(),
      heroApi.getAllHeroes()
    ])
    
    if (weaponResponse.code === 0) {
      weapons.value = weaponResponse.data || []
    } else {
      throw new Error(weaponResponse.message || '获取武器数据失败')
    }
    
    if (heroResponse.code === 0) {
      heroList.value = heroResponse.data || []
    } else {
      console.warn('获取英雄数据失败:', heroResponse.message)
      heroList.value = []
    }
    
  } catch (err) {
    console.error('加载数据失败:', err)
    error.value = '网络错误，请稍后重试'
    weapons.value = []
    heroList.value = []
  } finally {
    loading.value = false
  }
}

const loadAllWeapons = async () => {
  try {
    loading.value = true
    error.value = null
    
    const response = await weaponApi.getAllWeapons()
    
    if (response.code === 0) {
      weapons.value = response.data || []
    } else {
      throw new Error(response.message || '获取武器数据失败')
    }
    
  } catch (err) {
    console.error('加载武器失败:', err)
    error.value = '网络错误，请稍后重试'
    weapons.value = []
  } finally {
    loading.value = false
  }
}

const handleSearch = () => {
  // 搜索逻辑已在计算属性中处理
}

const handleFilter = async () => {
  if (!selectedHero.value) {
    // 如果没有选择英雄，加载所有武器
    await loadAllWeapons()
    return
  }
  
  try {
    loading.value = true
    error.value = null
    
    // 调用后端接口获取指定英雄的武器列表
    // 修复：确保传递为数字ID
    const heroId = Number(selectedHero.value)
    const response = await weaponApi.getWeaponsByHeroId(heroId)
    
    if (response.code === 0) {
      weapons.value = response.data || []
    } else {
      throw new Error(response.message || '获取武器数据失败')
    }
    
  } catch (err) {
    console.error('筛选武器失败:', err)
    error.value = '筛选失败，请稍后重试'
    ElMessage.error('筛选武器失败')
  } finally {
    loading.value = false
  }
}

const selectWeapon = (weapon) => {
  selectedWeapon.value = weapon
  showDetailModal.value = true
}

const closeDetailModal = () => {
  showDetailModal.value = false
  selectedWeapon.value = null
}

const handleImageError = (event) => {
  event.target.src = '/default-weapon.png'
}

const handleHeroImageError = (event) => {
  event.target.src = '/default-hero.png'
}

const getHeroInfo = (heroId) => {
  if (!heroId) return null
  return heroList.value.find(hero => hero.id === heroId)
}

const goToHeroDetail = (heroId) => {
  if (!heroId) return
  // 跳转到角色页面
  window.location.href = '/character'
}

// 组件挂载时加载数据
onMounted(async () => {
  await loadData()
})
</script>

<style scoped>
.weapon-display {
  min-height: calc(100vh - 70px);
  padding: 2rem;
  background: rgba(0, 0, 0, 0.7);
}

.page-header {
  text-align: center;
  margin-bottom: 2rem;
  color: white;
}

.page-header h1 {
  font-size: 2.5rem;
  margin-bottom: 0.5rem;
  background: linear-gradient(45deg, #ff6b6b, #4ecdc4);
  -webkit-background-clip: text;
  -webkit-text-fill-color: transparent;
  background-clip: text;
}

.page-header p {
  font-size: 1.1rem;
  opacity: 0.8;
}

.loading-container {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  min-height: 300px;
  color: white;
}

.loading-spinner {
  width: 50px;
  height: 50px;
  border: 3px solid rgba(255, 255, 255, 0.3);
  border-top: 3px solid #4ecdc4;
  border-radius: 50%;
  animation: spin 1s linear infinite;
  margin-bottom: 1rem;
}

@keyframes spin {
  0% { transform: rotate(0deg); }
  100% { transform: rotate(360deg); }
}

.error-container {
  text-align: center;
  padding: 2rem;
  color: #ff6b6b;
}

.retry-btn {
  background: #4ecdc4;
  color: white;
  border: none;
  padding: 0.5rem 1rem;
  border-radius: 5px;
  cursor: pointer;
  margin-top: 1rem;
}

.retry-btn:hover {
  background: #45b7aa;
}

.search-section {
  background: rgba(255, 255, 255, 0.1);
  padding: 1.5rem;
  border-radius: 10px;
  margin-bottom: 2rem;
}

.search-container {
  display: flex;
  gap: 1rem;
  align-items: center;
  flex-wrap: wrap;
}

.search-input-wrapper {
  position: relative;
  flex: 1;
  min-width: 250px;
}

.search-input {
  width: 100%;
  padding: 0.75rem 2.5rem 0.75rem 1rem;
  border: 2px solid rgba(255, 255, 255, 0.2);
  border-radius: 25px;
  background: rgba(255, 255, 255, 0.1);
  color: white;
  font-size: 1rem;
}

.search-input::placeholder {
  color: rgba(255, 255, 255, 0.6);
}

.search-input:focus {
  outline: none;
  border-color: #4ecdc4;
  background: rgba(255, 255, 255, 0.15);
}

.search-icon {
  position: absolute;
  right: 1rem;
  top: 50%;
  transform: translateY(-50%);
  color: rgba(255, 255, 255, 0.6);
}

.filter-container {
  display: flex;
  gap: 1rem;
}

.hero-filter {
  padding: 0.75rem 1rem;
  border: 2px solid rgba(255, 255, 255, 0.2);
  border-radius: 8px;
  background: rgba(255, 255, 255, 0.1);
  color: white;
  font-size: 1rem;
  min-width: 150px;
}

.hero-filter:focus {
  outline: none;
  border-color: #4ecdc4;
}

.hero-filter option {
  background: #2c3e50;
  color: white;
}

.weapons-grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(250px, 1fr));
  gap: 1.2rem;
  margin-bottom: 2rem;
}

.weapon-card {
  background: transparent;
  border-radius: 15px;
  padding: 1rem;
  border: 1px solid rgba(255, 255, 255, 0.2);
  transition: all 0.3s ease;
  cursor: pointer;
  display: flex;
  flex-direction: column;
  height: auto;
}

.weapon-card:hover {
  transform: translateY(-5px);
  background: rgba(255, 255, 255, 0.15);
  border-color: #4ecdc4;
  box-shadow: 0 10px 30px rgba(78, 205, 196, 0.3);
}

.weapon-image {
  width: 100%;
  margin-bottom: 1rem;
  border-radius: 10px;
  overflow: hidden;
  background: rgba(255, 255, 255, 0.05);
  display: flex;
  align-items: center;
  justify-content: center;
  min-height: 120px;
}

.weapon-image img {
  max-width: 100%;
  max-height: 200px;
  width: auto;
  height: auto;
  object-fit: contain;
}

.weapon-info {
  color: white;
}

.weapon-name {
  font-size: 1.2rem;
  margin-bottom: 0.5rem;
  color: #4ecdc4;
}

.weapon-stats {
  display: flex;
  flex-direction: column;
  gap: 0.3rem;
}

.stat-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.stat-label {
  color: rgba(255, 255, 255, 0.7);
  font-size: 0.9rem;
}

.stat-value {
  color: white;
  font-weight: bold;
}

.empty-state {
  text-align: center;
  padding: 3rem;
  color: rgba(255, 255, 255, 0.6);
}

.empty-icon {
  font-size: 4rem;
  margin-bottom: 1rem;
}

.empty-state h3 {
  margin-bottom: 0.5rem;
  color: white;
}

/* 模态框样式 */
.modal-overlay {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: rgba(0, 0, 0, 0.8);
  display: flex;
  align-items: center;
  justify-content: center;
  z-index: 1000;
  backdrop-filter: blur(5px);
}

.modal-content {
  background: rgba(255, 255, 255, 0.1);
  border-radius: 15px;
  backdrop-filter: blur(20px);
  border: 1px solid rgba(255, 255, 255, 0.2);
  max-width: 800px;
  width: 90%;
  max-height: 90vh;
  overflow-y: auto;
}

.modal-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 1.5rem;
  border-bottom: 1px solid rgba(255, 255, 255, 0.1);
}

.modal-header h2 {
  color: #4ecdc4;
  margin: 0;
}

.close-btn {
  background: none;
  border: none;
  color: white;
  font-size: 1.5rem;
  cursor: pointer;
  padding: 0.5rem;
  border-radius: 50%;
  width: 40px;
  height: 40px;
  display: flex;
  align-items: center;
  justify-content: center;
}

.close-btn:hover {
  background: rgba(255, 255, 255, 0.1);
}

.modal-body {
  padding: 1.5rem;
}

.weapon-detail-content {
  display: grid;
  grid-template-columns: 1fr 2fr;
  gap: 2rem;
  color: white;
}

.weapon-image-large {
  width: 100%;
  height: 250px;
  border-radius: 10px;
  overflow: hidden;
  background: rgba(255, 255, 255, 0.05);
}

.weapon-image-large img {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.weapon-details {
  display: flex;
  flex-direction: column;
  gap: 1.5rem;
}

.detail-section h3 {
  color: #4ecdc4;
  margin-bottom: 0.5rem;
  font-size: 1.1rem;
}

.stats-grid {
  display: grid;
  grid-template-columns: 1fr 1fr;
  gap: 1rem;
}

.stats-grid .stat-item {
  background: rgba(255, 255, 255, 0.05);
  padding: 0.75rem;
  border-radius: 8px;
  display: flex;
  flex-direction: column;
  align-items: center;
  text-align: center;
}

.stats-grid .stat-label {
  font-size: 0.9rem;
  color: rgba(255, 255, 255, 0.7);
  margin-bottom: 0.25rem;
}

.stats-grid .stat-value {
  font-size: 1.2rem;
  font-weight: bold;
  color: #4ecdc4;
}

.weapon-description,
.weapon-skill {
  line-height: 1.6;
  color: rgba(255, 255, 255, 0.9);
}

.hero-info {
  display: flex;
  align-items: center;
  gap: 15px;
  background: rgba(255, 255, 255, 0.05);
  padding: 15px;
  border-radius: 8px;
  margin-top: 10px;
  cursor: pointer;
  transition: all 0.3s ease;
}

.hero-info:hover {
  background: rgba(255, 255, 255, 0.1);
  transform: translateY(-2px);
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.3);
}

.hero-avatar {
  width: 60px;
  height: 60px;
  border-radius: 50%;
  overflow: hidden;
  border: 2px solid #4ecdc4;
  flex-shrink: 0;
}

.hero-avatar img {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.hero-details {
  flex: 1;
}

.hero-name {
  font-size: 1.1rem;
  font-weight: bold;
  color: #4ecdc4;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .weapon-display {
    padding: 1rem;
  }
  
  .search-container {
    flex-direction: column;
  }
  
  .search-input-wrapper {
    min-width: 100%;
  }
  
  .weapons-grid {
    grid-template-columns: 1fr;
  }
  
  .weapon-detail-content {
    grid-template-columns: 1fr;
  }
  
  .stats-grid {
    grid-template-columns: 1fr;
  }
}
</style>